package com.threeti.mecool.core.domain.model.project;

import com.threeti.mecool.framework.domain.support.DefaultDomainEntity;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.legacy.domain.model.basicdata.biz.SalesLegacy;
import org.apache.commons.lang.Validate;

import javax.persistence.*;
import java.util.List;

/**
 * 项目促销员
 */
@Entity
@Table(name = "DM_PROJECT_SALESPROMOTER",
        uniqueConstraints = @UniqueConstraint(columnNames = {"PROJECT", "SALES_PROMOTER"}))
public class ProjectSalesPromoter extends DefaultDomainEntity {

    @ManyToOne(optional = false)
    private Project project;

    @ManyToOne(optional = false)
    private SalesLegacy salesPromoter;

    @ManyToMany
    @JoinTable(name = "DM_PROJECT_SALESPROMOTER_STORE",
            joinColumns = {@JoinColumn(name = "PROJSALES_ID")},
            inverseJoinColumns = {@JoinColumn(name = "PROJSTORE_ID")})
    private List<ProjectStore> assignedStores = Lists.newArrayList();

    public ProjectSalesPromoter(Project project, SalesLegacy salesPromoter) {
        super();
        this.project = project;
        this.salesPromoter = salesPromoter;
    }

    /**
     * 取得促销员所在项目
     */
    public Project getProject() {
        return project;
    }

    /**
     * 取得促销员
     */
    public SalesLegacy getSalesPromoter() {
        return salesPromoter;
    }

    /**
     * 取得被分配给本促销员的门店们
     */
    public List<ProjectStore> getAssignedStores() {
        return assignedStores;
    }

    /**
     * 为本促销员批量分配门店
     */
    public ProjectSalesPromoter assignStores(List<ProjectStore> stores) {
        Validate.notNull(stores, "分配的门店不能为空");
        setAssignedStores(stores);
        return this;
    }

    /**
     * 为本促销员分配门店
     */
    public ProjectSalesPromoter assignStore(ProjectStore store) {
        Validate.notNull(store, "分配的门店不能为空");
        Validate.notNull(store.getId(), "分配的门店必须已经存在");

        if (assignedStores.contains(store)) {
            throw new RuntimeException("无法分配,门店无法重复分配给促销员" + store);
        }
        assignedStores.add(store);
        return this;
    }

    /**
     * 和已绑定的所有门店解除绑定关系
     */
    public ProjectSalesPromoter unbindWithAllAssignedStores() {
        this.assignedStores = null;
        return this;
    }

    /**
     * 和已绑定的特定门店解除绑定关系
     */
    public ProjectSalesPromoter unbindWithSpecifiedAssignedStore(List<ProjectStore> projStoresNeedToBeUnbinded) {
        if (this.assignedStores != null) this.assignedStores.removeAll(projStoresNeedToBeUnbinded);
        return this;
    }

    /**
     * 强制刷新门店的绑定
     */
    public void setAssignedStores(List<ProjectStore> assignedStores) {
        this.assignedStores = assignedStores;
    }

    ProjectSalesPromoter() {
        super();
    }

}
